/*
 * Copyright (c) 2008 Frederic Daoud
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.stripesbook.article.action;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontValidate;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StrictBinding;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import net.sourceforge.stripes.validation.ValidationErrors;
import net.sourceforge.stripes.validation.ValidationMethod;

import org.stripesbook.article.model.Database;
import org.stripesbook.article.model.User;
import org.stripesbook.article.view.LoginView;
import org.stripesbook.rayures.action.RayuresBaseActionBean;

@UrlBinding("/login")
@StrictBinding
public class LoginActionBean extends RayuresBaseActionBean {

  @ValidateNestedProperties({
    @Validate(field="username", required=true),
    @Validate(field="password", required=true)
  })
  private User user;

  /* Getters and setters for user */
  public User getUser() {
    return user;
  }
  public void setUser(User user) {
    this.user = user;
  }

  @DefaultHandler
  @DontValidate
  public void view() {
  }

  @Override
  public Object getView() {
    return tag(LoginView.class);
  }

  @ValidationMethod
  public void validateUsernameAndPassword(ValidationErrors errors) {
    User existingUser = Database.getUser(user.getUsername());

    if (existingUser == null) {
      errors.add("user.username",new SimpleError("The username is not valid"));
    }
    else if (!existingUser.getPassword().equals(user.getPassword())) {
      errors.add("user.password",new SimpleError("The password is not valid"));
    }
  }

  public Resolution login() {
    User existingUser = Database.getUser(user.getUsername());

    if (!existingUser.isActivated()) {
      return new RedirectResolution(ActivateActionBean.class)
        .addParameter("user.username", existingUser.getUsername());
    }
    getContext().getRequest().getSession(true).setAttribute("user",existingUser);
    return new RedirectResolution(SecuredActionBean.class);
  }
}
